<template>
	<div class="AI-analysis">
		<nav-header></nav-header>
        <div class="zh-table">
            <div class="zh-table-open clear">
                <div class="zh-open-left fl">
                    <div class="open-width" style="width: 270px">
                        <el-input v-model="keyword" placeholder="请输入 mac 搜索" @keyup.enter.native="searchFunc"></el-input>
                    </div>
                    <el-button type="primary" @click="searchFunc" >搜索</el-button>
                    <el-button type="primary" @click="reset" >重置</el-button>

                </div>
            </div>
            <div class="zh-table-contents"
                v-loading="loading.status"
                :element-loading-text="loading.txt"
                v-loading.fullscreen.lock="loading.full">
                <el-table
                    :data="listData"
                    border
                    max-height="600"
                    style="width: 100%">
                    <el-table-column
                        prop="recorder_id"
                        label="关联设备"
                        align="center"
                        show-overflow-tooltip
                        >
                        <template slot-scope="scope">
                            <span @click="checkRecorder(scope.row.recorder_id)" style="color: #66b1ff; cursor: pointer;">{{scope.row.recorder_id.length > 1 ? '已绑定' : '未绑定'}}</span>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column
                        prop="school_name"
                        label="学校"
                        align="center"
                        show-overflow-tooltip
                        >
                    </el-table-column> -->
                    <el-table-column
                        prop="ip"
                        label="IP"
                        align="center"
                        show-overflow-tooltip
                        >
                    </el-table-column>
                    <el-table-column
                        prop="mac"
                        label="mac"
                        align="center"
                        show-overflow-tooltip
                        >
                    </el-table-column>
                    <el-table-column
                        prop="port"
                        label="端口"
                        align="center"
                        show-overflow-tooltip
                        >
                    </el-table-column>
                    <el-table-column
                        prop="rate"
                        label="发送频率"
                        align="center"
                        show-overflow-tooltip
                        >
                    </el-table-column>
                    <el-table-column
                        prop="register_time"
                        label="注册时间"
                        align="center"
                        show-overflow-tooltip
                        >
                    </el-table-column>
                    <el-table-column
                        prop="is_online"
                        label="在线状态"
                        align="center"
                        show-overflow-tooltip
                        >
                        <template slot-scope="scope">
                            <span>{{scope.row.is_online == 0 ? '离线' : '在线'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop=""
                        label="状态"
                        align="center"
                        show-overflow-tooltip
                        >
                        <template slot-scope="scope">
                            <span>{{scope.row.status == 0 ? '停用' : '启用'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop=""
                        label="操作"
                        align="center"
                        width="140"
                        >
                        <template slot-scope="scope">
                            <el-button @click="saveBox(scope.row)" type="text">编辑</el-button>
                            <!-- <el-button @click="delete_confirm(scope.row)" type="text" class="delete-button">删除</el-button> -->
                        </template>
                    </el-table-column>
                </el-table>
                <div class="table-pagination" v-show="total_number > 10">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="listParam.page_index"
                        :page-sizes="[10, 20, 30, 40, 50, 100]"
                        :page-size="listParam.page_size"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total_number">
                    </el-pagination>
                    <div class="pagination-button">
                        <el-button 
                            @click="getList"
                            type="primary" icon="el-icon-refresh" 
                            circle title="刷新数据" size="mini" >
                        </el-button>
                    </div>
                </div>
            </div>
        </div>
		<!-- 新增设备 -->
		<el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="编辑设备" :visible.sync="NewEquipment" width="500px" v-loading="loading.status" :element-loading-text="loading.txt">
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" status-icon label-position="right" label-width="140px" class="demo-ruleForm">
                <el-form-item label="关联设备：" prop="recorder" class="recorder-item">
                    <el-checkbox-group v-model="ruleForm.recorder">
                        <el-checkbox v-for="(item, index) in deviceData" :key="index" :label="item.name" name="type"></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="学校：" prop="school_id">
                    <el-select v-model="ruleForm.school_id" placeholder="请选择学校">
                        <el-option
                            v-for="item in schoolList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="采样频率（秒）：" prop="rate">
                    <el-input v-model="ruleForm.rate"></el-input>
                </el-form-item>
				<el-form-item label="状态：">
					<el-radio-group v-model="ruleForm.status">
					    <el-radio label="0">停用</el-radio>
					    <el-radio label="1">启用</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="cancelForm">取消</el-button>
				<el-button type="primary" @click="submitForm">确定</el-button>
			</div>
		</el-dialog>
        <el-dialog
            title="关联设备"
            :visible.sync="recorderVisible"
            width="500px"
            :before-close="recorderClose">
            <div v-if="deviceName.length > 0" class="recorder-list">
                <span v-for="(item, index) in deviceName" :key="index">{{item}}</span>
            </div>
            <div v-else style="padding-bottom: 20px">暂无数据</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="recorderClose">取 消</el-button>
                <el-button type="primary" @click="recorderClose">确 定</el-button>
            </span>
    </el-dialog>
	</div>
</template>
<script>
  	export default {
	    data() {
		    return {
		    	loading:{
					status:false,
					txt:'获取数据...',
					full:false
				},
                listData:[],
                schoolList: [],
		    	listParam:{
		       		keyword: '',
		       		page_index:1,
		       		page_size:10,
				},
				keyword: '',
		        total_number:0,
			    NewEquipment: false,
			    ruleForm: {
                    id: null,
                    recorder: [],
                    school_id: null,
                    rate: 30,
                    status: '1', 
			    },
			    rules: {
                    recorder: [
                        { type: 'array', required: true, message: '请至少选择一个关联设备', trigger: 'change' }
                    ],
                    school_id: [
                        { required: true, message: '请选择学校', trigger: 'change' }
                    ],
		            rate: [
        	            { required: true, message: '请输入发送频率', trigger: 'blur' },
                        { validator: this.validateRate, trigger: 'blur' }
        	        ],
                },
                recorderVisible: false,
                deviceName: [],
                deviceData: [],
                deviceNum : 0,
                totaldeviceNum: 1,
                deviceParam: {
		       		type: [0, 1, 2, 10],
		       		page_index: 1,
		       		page_size: 10,
                }
		   	}	
		},
		created(){
            this.getList();
            this.getDevice();
            this.getSchool();
	    },
	    watch:{
	    	NewEquipment(){
	    		if (this.NewEquipment === false)
	    			this.$refs.ruleForm.resetFields()
            },
            deviceNum() {
                if (this.totaldeviceNum != this.deviceNum) {
                    this.totaldeviceNum++;
                    this.deviceParam.page_index++;
                    this.getDevice();
                }
            },
        },
		methods: {
            getSchool() {
            	let success = (res =>{
                    this.schoolList = res.data;
            	})

            	this.$ajax.get('api/ai/school_list',{func:{success: success}})
            },
            validateRate(rule, value, callback) {
                let res = /^\d+$/;
                if (value === '') {
                    callback(new Error('请输入发送频率'));
                } else if (value > 120 || value < 10) {
                    callback(new Error('发送频率在 10 - 120 之间'));
                } else if (!res.test(value)) {
                    callback(new Error('发送频率只能填写数字'));
                } else {
                    callback();
                }
            },
            checkRecorder(id) {
                let res = id.split(',');
                res.shift();
                res.pop();

                if (is_empty(this.deviceData) && is_empty(res)) {
                    return false;
                } else {
                    this.deviceName = [];
                    this.deviceData.forEach(item => {
                        res.forEach(mes => {
                            if (item.id == mes) {
                                this.deviceName.push(item.name)
                            }
                        })
                    })

                    this.recorderVisible = true;
                }
            },
            recorderClose() {
                this.recorderVisible = false;
            },
			searchFunc(){
				this.listParam.keyword = this.keyword;
				this.listParam.page_index = 1;
				this.getList();
			},
			reset() {
				this.keyword = '';
				this.listParam = {
					keyword: '',
		       		page_index: 1,
		       		page_size: 10,
				}
				this.getList();
			},
			saveBox(obj){
                let name = [];
                let res = obj.recorder_id.split(',');
                res.shift();
                res.pop();

                if (!is_empty(this.deviceData) && !is_empty(res)) {
                    this.deviceData.forEach(item => {
                        res.forEach(mes => {
                            if (item.id == mes) {
                                name.push(item.name)
                            }
                        })
                    })
                }

                this.ruleForm.id =  obj.id;
                this.ruleForm.recorder = name;
                this.ruleForm.school_id = obj.school_id;
                this.ruleForm.rate = obj.rate;
                this.ruleForm.status =  obj.status.toString();
                this.NewEquipment = true;
			},
			cancelForm(){
				this.NewEquipment = false
				this.$refs['ruleForm'].resetFields();
			},
			submitForm(){
				this.$refs.ruleForm.validate((valid) => {
	     			if (valid) {
	     				this.loading.txt = '正在保存...';
                        this.loading.status = true;
                        this.loading.full = true;
                        
                        let success = ( data => {
                            this.NewEquipment = false;
                            this.loading.status = false;
                            this.loading.full = false;
                            this.loading.txt = '获取数据...';
                            this.$message.success(data.msg)
                            this.cancelForm();
                            this.getList();
                        });

                        let fail = ( data=>{
                            this.loading.status = false;
                            this.loading.full = false;
                            this.loading.txt = '获取数据...';
                            this.$message.error(data.msg);
                        })

                        let temp = ',';
                        this.deviceData.forEach(item => {
                            this.ruleForm.recorder.forEach(mes => {
                                if (item.name == mes) {
                                    temp = temp + item.id  + ','
                                }
                            })
                        })

                        let params = {
                            id: this.ruleForm.id,
                            school_id: this.ruleForm.school_id,
                            rate: this.ruleForm.rate,
                            status: this.ruleForm.status,
                            recorder_id_str: temp
                        }
                        
                        this.$ajax.post('api/ai/machine_info', params, {func: {success: success, fail: fail}})
	     			} else {
		  				return false
		  			}
		  		});
			},
		    getList(){
		    	this.loading.status = true;
            	let success = (data=>{
            		this.loading.status = false;
            		this.listData = data.data.data;
            		this.total_number = data.data.page_sum;
            	})
            	let fail = ( data => {
            		this.loading.status = false;
            		this.$message.error(data.msg)
            	})

            	this.$ajax.get('api/ai/machine_list',{params: this.listParam, func:{success: success, fail: fail}})
            },
            getDevice() {
            	let success = (data=>{
                    if (this.deviceData.length > 0) {
                        data.data.data.forEach(item => {
                            this.deviceData.push(item);
                        })
                    } else {
                        this.deviceData = data.data.data;
                    }
                    this.deviceNum = data.data.page_max;
            	})
            	let fail = ( data => {
            		this.$message.error(data.msg)
            	})

            	this.$ajax.get('api/recorder/recorder_list', {params: this.deviceParam, func: {success: success, fail: fail}})
            },
		    delete(id){
		    	let success = ( data => {
                    this.$message.success(data.msg);
                    
                    if (this.listData.length - 1 === 0) {
						if (this.listParam.page_index > 1) {
							this.listParam.page_index-- ;
						} else {
							this.listParam.page_index = 1;
						}
					}

					this.getList();
				});
		    	this.$ajax.delete('api/ai/machine_info',{params:{id:id},func:{success:success}})
		    },
		    delete_confirm(obj){
				let yes = ( data => {
					this.delete(obj.id);
				})
				let cancel = ( data => {})
				this.e_confirm({yes:yes,cancel:cancel,txt:'确定将该设备删除吗？'});
			},
		    handleSizeChange(val) {
		     	this.listParam.page_index = 1;
		    	this.listParam.page_size = val;
		    	this.getList()
		    },
		    handleCurrentChange(val) {
		    	this.listParam.page_index = val;
		    	this.getList();
		    },
		},
  	}
</script>
<style lang="scss">
	.AI-analysis {
		.el-table__body-wrapper table tbody {
			td:nth-child(8) {
				padding: 0;
			}
			.el-loading-mask {
				height: 40px;
				line-height: 40px;
				.el-loading-spinner {
				    margin-top: -20px;
				    height: 40px;
				    line-height: 40px;
				    .circular {
				    	height: 32px;
    					line-height: 32px;
				    }
				}
			}
		}

        .recorder-list {
            display: flex;
            justify-content: center;
            align-items: center;
            flex-wrap: wrap;

            >span {
                padding-right: 20px;
                padding-bottom: 20px;
            }
        }

        .recorder-item {
            >div {
                .el-checkbox+.el-checkbox {
                    margin-left: 0;
                }

                .el-checkbox-group >label {
                    margin-right: 30px;
                }
            }
        }
	}
	.masking{
		display: block;
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		transition: .5s;
		background: rgba(0,0,0,.3);
		z-index: 4;
		.maskingBox{
			position: absolute;
			top: 20%;
			left: 50%;
			width: 800px;
			margin-left: -400px;
			background: #fff;
		}
		.masking_h{
			padding: 10px 15px;
			background: #348EFC;
			text-align: center;
			text-align-last: justify;
			>span,
			>i{
				font-size: 16px;
				text-align-last: initial;
				display: inline-block;
				vertical-align: middle;
				color: #fff;
			}
			>i{
				cursor: pointer;
			}
		}

	}

	.activeLive{
		opacity: 0;
		visibility: hidden;
	}
</style>